package com.share.config;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.constants.Constants;
import com.share.constants.UserType;
import com.share.mapper.LoginMapper;
import com.share.pojo.domain.Login;
import com.share.utils.NameUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class BootstrapListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, Constants.System.SYSTEM_ADMIN)
                .eq(Login::getName, Constants.System.SYSTEM_ADMIN)
        );
        if(login == null){//没有查询到就进行初始化
            Login loginAdmin = new Login();
            long id = IdUtil.getSnowflake(0L, 0L).nextId();
            loginAdmin.setId(id);
            loginAdmin.setAvatar("https://img.duoziwang.com/2018/11/022421241827374047.jpg");
            loginAdmin.setAdmin(true);
            loginAdmin.setDeleted(false);
            loginAdmin.setEnabled(true);
            loginAdmin.setType(UserType.admin);
            loginAdmin.setName(Constants.System.SYSTEM_ADMIN);
            loginAdmin.setNickName(NameUtil.getName());
            loginAdmin.setCreateTime(new Date());
            loginAdmin.setUsername(Constants.System.SYSTEM_ADMIN);
            //密码要加密
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            loginAdmin.setPassword(encoder.encode("123456"));
            loginMapper.insert(loginAdmin);
        }
    }
}
